#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    //设置主窗口名称
    this->setWindowTitle("LSB");
}

MainWindow::~MainWindow()
{
    delete ui;
}

/*
读取图片按钮
*/
void MainWindow::on_pushButton_clicked()
{
//    QString filePath = "D:/搜狗高速下载/信安/可供选用的图片/可供选用的图片/24位真彩图/LENA_COLOR.BMP";
    QString filePath = QFileDialog::getOpenFileName(
                this,
                tr("Open File"),
                NULL,// ".",
                tr("*.bmp"));
    if(filePath == NULL){
        return;
    }

    QString fileName = filePath.split("/").last();  //文件名
    //ui->textBrowser->append("Open file:"+fileName);
    appendMsg("Open file: ",fileName);
    ui->textEdit->setText("");

    QImage img = QImage(filePath);
    QLabel *label = ui->pic_0;
//    img = img.scaled(label->width(),label->height(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
    QPixmap pixmap = QPixmap::fromImage(img);
    pixmap = pixmap.scaled(label->width(),label->height(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
    ui->pic_0->setPixmap(pixmap);

    ui->pic_1->setText("Target Picture");

    if(analyzeWrite != nullptr){ //如果之前读取过图片数据，就释放之前的数据资源
        delete analyzeWrite;
        analyzeWrite = nullptr;
    }

    ByteArrayList *writeTo = readFromFile(filePath);
    ByteArrayList *list = writeTo;
    if(list == nullptr){                    //读取文件失败
        //ui->textBrowser->append("Error:File "+fileName+" doesn't exist.");
        appendError("File "+fileName+" doesn't exist.");
        return;
    }
    analyzeWrite = new AnalyzeBmp(writeTo);

    //ui->textBrowser->append("Succeed!");    //成功读取图片
    appendMsg("Succeed!");
    QString colorType = NULL;
    if(analyzeWrite->getType_biBitCount() == 24){
        colorType = "true color";
    }else{
        colorType = QString::number(1 << analyzeWrite->getType_biBitCount());
    }
    appendMsg("","The file type is <font style='color:green'><b>"+colorType+"</b></font>.");

    if(analyzeWrite->getMaxByte() <= 0){
        appendError("Nothing can be inserted.");
    }
    ui->textBrowser->append("The max bytes you can insert is <b>"+QString::number(analyzeWrite->getMaxByte())+"</b>.");

//    AnalyzeBmp *ab = new AnalyzeBmp(list);
//    ab->writeMsg("jfdadhkhkfhfahlhfhadslfhadfjkdadhlfadkjfhaldhfla");
//    QFile target("target.bmp");
//    target.open(QIODevice::WriteOnly);

//    for (int i = 0;i < ab->getSourceList()->size();i++) {
//        target.write(ab->getSourceList()->at(i));
//    }


//    target.close();
}

/*
嵌入
*/
void MainWindow::on_pushButton_2_clicked()
{
    AnalyzeBmp *analyzeWrite = this->analyzeWrite;
    if(analyzeWrite == nullptr){
        //ui->textBrowser->append("Error:No file is selected.");
        appendError("No file is selected.");
        return;
    }
    if(analyzeWrite->getDataPtr() > (int)analyzeWrite->getFileHeader().bfOffBits){    //已经嵌入过
        //ui->textBrowser->append("Error:You clicked me too fast.");
        appendError("You clicked me too fast.");
        return;
    }
    if(ui->textEdit->toPlainText() == NULL){    //没有提供写入的信息
        //ui->textBrowser->append("Error:Nothing need to insert.");
        appendError("Nothing need to be inserted.");
        return;
    }
    //ui->textBrowser->append("Inserting...");
    appendMsg("Inserting...");
    analyzeWrite->setLSBtoZero();
    if(!analyzeWrite->writeMsg(ui->textEdit->toPlainText())){   //写入失败
        //ui->textBrowser->append("Error:Can't write so much words.");
        appendError("Can't write so much words.");
        return;
    };
    appendMsg("Done!");
//    QFile target("target.bmp");
//    target.open(QIODevice::WriteOnly);

//    int head = (analyzeWrite->getType_biBitCount() == 24) ? 54 : 58;
//    int rate = 100;
//    int r = 0;
//    for (int i = 0;i < analyzeWrite->getSourceList()->size();i++) {
//        head = (i != 0) ? 0:((analyzeWrite->getType_biBitCount() == 24) ? 54 : 58);
//        for(int j=head;j<analyzeWrite->getSourceList()->at(i).size();j++){
//            char c = analyzeWrite->getSourceList()->operator[](i).operator[](j);
//            r = rand()%rate;
//            if(r == 1){
//                c += (BYTE)(128*generateGaussianNoise());
//             }
//             analyzeWrite->getSourceList()->operator[](i).operator[](j) = c;
//        }

//    }
//    for (int i = 0;i < analyzeWrite->getSourceList()->size();i++) {
//        target.write(analyzeWrite->getSourceList()->at(i));
//    }


//    target.close();
//    //ui->textBrowser->append("Done!");
//    appendMsg("Done!");
}

/*
提取图片    已弃用
*/
void MainWindow::on_pushButton_3_clicked()
{
//    QString filePath = QFileDialog::getOpenFileName(
//                this,
//                tr("Open File"),
//                NULL,// ".",
//                tr("*.bmp"));
//    if(filePath == NULL){
//        return;
//    }
//    QString fileName = filePath.split("/").last();  //文件名
//    //ui->textBrowser->append("<font style='color:red'><b>Open file</b></font>:"+fileName);
//    appendMsg("Open file: ",fileName);
//    ui->textEdit->setText("");

//    QImage img = QImage(filePath);
//    QLabel *label = ui->pic_1;
////    img = img.scaled(label->width(),label->height(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
//    QPixmap pixmap = QPixmap::fromImage(img);
//    pixmap = pixmap.scaled(label->width(),label->height(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
//    label->setPixmap(pixmap);

//    if(analyzeRead != nullptr){ //如果之前读取过图片数据，就释放之前的数据资源
//        delete analyzeRead;
//        analyzeRead = nullptr;
//    }

//    ByteArrayList *readFrom = readFromFile(filePath);
//    analyzeRead = new AnalyzeBmp(readFrom);

//    ByteArrayList *list = readFrom;
//    if(list == nullptr){                    //读取文件失败
//        //ui->textBrowser->append("Error:File "+fileName+" doesn't exist.");
//        appendError("File "+fileName+" doesn't exist.");
//        return;
//    }
//    //ui->textBrowser->append("Succeed!");    //成功读取图片
//    appendMsg("Succeed!");
}


/*
提取
*/
void MainWindow::on_pushButton_4_clicked()
{
    analyzeRead = analyzeWrite;
    if(analyzeRead == nullptr){
        //ui->textBrowser->append("Error:No file is selected.");
        appendError("No file is selected.");
        return;
    }
    if(analyzeRead->getDataPtr() > (int)analyzeRead->getFileHeader().bfOffBits){    //已经提取过
        //ui->textBrowser->append("Error:You clicked me too fast.");
        appendError("You clicked me too fast.");
        return;
    }
    //ui->textBrowser->append("Reading...");
    appendMsg("Reading...");

    QString msg = analyzeRead->readMsg();

    if(msg == NULL){   //提取失败
        //ui->textBrowser->append("Error:Nothing is read.");
        appendError("Nothing is read.");
        return;
    };

    ui->textEdit->setText(msg);
    //ui->textBrowser->append("Done!");
    appendMsg("Done!");

}

void MainWindow::appendError(QString s){
    ui->textBrowser->append("<font style='color:red'><b>Error:</b></font> "+s);
}

void MainWindow::appendMsg(QString green, QString plain){
    ui->textBrowser->append("<font style='color:green'><b>"+green+"</b></font> "+plain);
}

/*
添加噪声
*/
void MainWindow::on_pushButton_5_clicked()
{
    if(analyzeWrite == nullptr){
        appendError("No file is loaded.");
        return;
    }

    appendMsg("Add noise...");
    int head = (analyzeWrite->getType_biBitCount() == 24) ? 54 : 58;
    int rate = 5;
    int r = 0;
    srand(time(NULL));
    int head0 = analyzeWrite->getFileHeader().bfOffBits / analyzeWrite->getSourceList()->getMaxSizeEachArray();
    for (int i = head0;i < analyzeWrite->getSourceList()->size();i++) {
        head = (i == head0) ? analyzeWrite->getFileHeader().bfOffBits % analyzeWrite->getSourceList()->getMaxSizeEachArray():0;
        for(int j=head;j < analyzeWrite->getSourceList()->at(i).size();j++){
            char c = analyzeWrite->getSourceList()->operator[](i).operator[](j);
            r = rand()%rate;
            if(r == 0){
                BYTE b = (BYTE)(128*generateGaussianNoise()) + BYTE(r);
                if((BYTE)(c+b) < c){
                    c = (BYTE)255;
                }else{
                    c += b;
                }

             }
             analyzeWrite->getSourceList()->operator[](i).operator[](j) = c;
        }

    }
    appendMsg("Done!");
}
/*
存储图片
*/
void MainWindow::on_pushButton_6_clicked()
{
    if(analyzeWrite == nullptr){
        appendError("No file is loaded.");
        return;
    }
    appendMsg("Saving...");

    QFile target("target.bmp");
    target.open(QIODevice::WriteOnly);


    for (int i = 0;i < analyzeWrite->getSourceList()->size();i++) {
        target.write(analyzeWrite->getSourceList()->at(i));
    }


    target.close();
    //ui->textBrowser->append("Done!");

    QImage img = QImage("target.bmp");
    QLabel *label = ui->pic_1;
//    img = img.scaled(label->width(),label->height(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
    QPixmap pixmap = QPixmap::fromImage(img);
    pixmap = pixmap.scaled(label->width(),label->height(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
    ui->pic_1->setPixmap(pixmap);


    appendMsg("Done!");
}
